'''
redis做缓存
'''
import pickle

import pymysql
import redis


def load_depts_from_db():
    con = pymysql.connect(host='localhost',
                          port=3306,
                          user='root',
                          password='root',
                          database='hrs',
                          charset='utf8')
    depts = ()
    try:
        with con.cursor() as cursor:
            cursor.execute('select * from tb_dept')
            depts = cursor.fetchall()
    except pymysql.MySQLError as err:
        print(err)
    finally:
        con.close()
    return depts


def main():
    client = redis.Redis(host='localhost', port=6379, password='smile132')
    data = client.get('depts')
    if data:
        depts = pickle.loads(data)
    else:
        depts = load_depts_from_db()
        client.set('depts', pickle.dumps(depts))
    print(depts)


if __name__ == '__main__':
    main()
